<template>
  <div>
    <common-page
      ref="common"
      :ccode="ccode"
      @hook:created="commonCreated"
      @btnClick="btnClick"
    />
    <user-select :outerTag="outerTag" :multi="false" user2Local="1" :dialog-visible.sync="dialogVisible" @confirm="handleUserConfirm" />
    <common-dialog
      ref="commonDialog"
      :dialog-visible.sync="transferDialog"
      title="转办"
      width="500px"
      @confirm="handleConfirm"
    >
      <div v-if="transferDialog">
        <el-form ref="transferForm" :model="transferForm" size="small" :rules="transferRules" label-width="100px">
          <el-form-item label="可转办任务" prop="oInsId">
            <el-select v-model="transferForm.oInsId" style="width:300px;" placeholder="请选择可转办任务" @focus="handleInsFocus">
              <el-option v-for="(item,index) in transferTasks" :key="index" :label="item.displayName" :value="item.oinsId" />
            </el-select>
          </el-form-item>
          <el-form-item label="转变到" prop="toUserId">
            <el-select v-model="transferForm.toUserId" style="width:300px;" placeholder="请选择" @focus="dialogVisible=true">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
    </common-dialog>
    <!-- 加签弹框 -->
    <user-select :outerTag="outerTag" :multi="true" user2Local="1" :dialog-visible.sync="apostilleDialog" @confirm="handleApostilleConfirm" />
    <common-dialog
      :dialog-visible.sync="backDialog"
      title="退回"
      width="600px"
      @confirm="handleBackConfirm"
    >
      <div v-if="backDialog">
        <el-form ref="backForm" :model="backForm" size="small" :rules="backRules" label-width="120px">
          <el-form-item label="退回到任务节点" prop="oInsId">
            <el-select v-model="backForm.oInsId" style="width:380px;" placeholder="请选择退回的任务节点" @focus="handleBackInsFocus">
              <el-option v-for="(item,index) in backTasks" :key="index" :label="item.displayName" :value="item.taskId" />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
    </common-dialog>
  </div>
</template>

<script>
import {
  getFormData,
  saveFormData,
  invokeMethod
} from '@/api/common'
import {
  commonInvoke,
} from '@admin/api/common.js'
import UserSelect from '@admin/components/userSelect/index'
import {
  findComponentDownward,
  getUnionArr,
  collectPluck
} from '@/utils/index'

export default {
  name: 'WorkflowMonitor',
  components: {
    UserSelect
  },
  data() {
    return {
      currentBtn: {},
      currentRow: {},
      dialogVisible: false, // 选人弹框
      transferDialog: false,
      backDialog: false,
      apostilleDialog: false,
      transferForm: {
        oInsId: '',
        toUserId: '',
        toUserName: ''
      },
      transferTasks: [],
      transferRules: {
        oInsId: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        toUserId: [
          { required: true, message: '请选择', trigger: 'change' }
        ]
      },
      backForm: {
        oInsId: ''
      },
      backTasks: [],
      backRules: {
        oInsId: [
          { required: true, message: '请选择', trigger: 'change' }
        ]
      },
      outerTag: window.g?.userSelect?.outerTag || '0',
    }
  },
  computed: {
    ccode: function() {
      return this.$route.meta.code
    },
    options: function() {
      if (this.transferForm.toUserId) {
        return [{
          label: this.transferForm.toUserName,
          value: this.transferForm.toUserId
        }]
      } else {
        return []
      }
    }
  },
  watch: {
    transferDialog: function(newValue) {
      if (!newValue) {
        this.transferForm.oInsId = ''
        this.transferForm.toUserId = ''
        this.transferForm.toUserName = ''
      }
    },
    backDialog: function(newValue) {
      if (!newValue) {
        this.backForm.oInsId = ''
      }
    }
  },
  mounted: function() {
  },
  methods: {
    btnClick({ btn, currentRow }) {
      console.log(btn)
      let id = (btn.renderSetting || {}).id || '' // 唯一标识
      this.currentBtn = btn
      this.currentRow = currentRow
      if (btn.code === '1281305559127035906' || id=='wfForward') {
        this.transferDialog = true
      } else if (btn.code === '1281305559127035907' || id=='wfBack') {
        this.backDialog = true
      } else if (btn.code === '1124846700817551360'){
        this.apostilleDialog = true
      } else if (btn.code === '1281305559127035905'){
        this.$prompt('请输入废弃原因', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /\S+/,
          inputErrorMessage: '废弃原因不能为空'
        }).then(({ value }) => {
          var data = JSON.parse(JSON.stringify(currentRow))
          data.memo = value
          const param = {
            data,
            funcCode: btn.code,
            pageId: window.$CD.pageId
          }
          commonInvoke(param, true).then(()=>{
            this.$$success('废弃成功')
            this.$table.refresh()
          })
        }).catch((e) => {
          console.error(e);
          this.$message({
            type: 'info',
            message: '已取消'
          });       
        });
      }
    },
    // 选人确认
    handleUserConfirm(users) {
      const user = users[0]
      this.transferForm.toUserId = user.id
      this.transferForm.toUserName = user.user_code + '(' + user.user_name + ')'
      this.dialogVisible = false
    },
    // 获取转办任务
    handleInsFocus() {
      const params = {
        methodId: '943214791009243136',
        data: {
          fInsId: this.currentRow.id
        }
      }
      invokeMethod(params).then((res) => {
        this.transferTasks = res.data
      })
    },
    // 转办
    handleConfirm() {
      this.$refs.transferForm.validate(validate => {
        if (validate) {
          const params = {
            methodId: '928610088191528970',
            data: {
              oInsId: this.transferForm.oInsId,
              toUserId: this.transferForm.toUserId
            }
          }
          invokeMethod(params).then((res) => {
            if (res.success) {
              this.$$success('转办成功')
              this.transferDialog = false
              this.$table.refresh()
            }
          })
        }
      })
    },
    // 获取退回节点
    handleBackInsFocus() {
      const params = {
        methodId: '943448033159286784',
        data: {
          fInsId: this.currentRow.id
        }
      }
      invokeMethod(params).then((res) => {
        this.backTasks = res.data
      })
    },
    // 退回
    handleBackConfirm() {
      this.$refs.backForm.validate(validate => {
        if (validate) {
          const params = {
            methodId: '943833597322727424',
            data: {
              fInsId: this.currentRow.id,
              taskId: this.backForm.oInsId
            }
          }
          invokeMethod(params).then((res) => {
            if (res.success) {
              this.$$success('退回成功')
              this.backDialog = false
              this.$table.refresh()
            }
          })
        }
      })
    },
    // 加签
    handleApostilleConfirm(users) {
      if(users.length === 0){
        this.$$message('请选择')
        return
      }
      let userIds = users.map(i=>i.id).join(',')
      const params = {
        methodId: '1124828272446672896',
        data: {
          fInsId: this.currentRow.id,
          userIds: userIds
        }
      }
      invokeMethod(params).then((res) => {
        if (res.success) {
          this.$$success('处理成功')
          this.apostilleDialog = false
          this.$table.refresh()
        }
      })
    },
    commonCreated() {
    }
  }
}
</script>
